package kr.pe.okjsp.rss;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * RSS Feed 를 local로 연결해주는 모듈
 * @author kenu
 *
 */
public class RSSProxy {
	static Map pool = new HashMap();
	/**
	 * RSS feed를 가져옵니다. 기본charset은 utf-8 입니다. cached
	 *
	 * @param urlPath RSS URL path
	 * @return feed String
	 * @throws IOException
	 */
	public static String getCachedXML(String urlPath, String refresh) throws IOException {
		return getCachedXML(urlPath, "utf-8", refresh);
	}

	/**
	 * @param urlPath
	 * @param charset
	 * @param refresh "1" for refresh data
	 * @return feed String
	 * @throws IOException
	 */
	public static String getCachedXML(String urlPath, String charset, String refresh) throws IOException {
		String feed = (String)pool.get(urlPath);
		if (feed == null || "1".equals(refresh)) {
			feed = getXML(urlPath, "utf-8");
			if (feed.length() != 0) {
				pool.put(urlPath, feed);
			}
		}
		return feed;
	}

	/**
	 * charset에 따른 RSS feed를 가져옵니다.
	 *
	 * @param urlPath
	 * @param charset
	 * @return feed
	 * @throws IOException
	 */
	public static String getXML(String urlPath, String charset) throws IOException {
		InputStream openStream = new URL(urlPath).openStream();
		InputStreamReader isr = new InputStreamReader(openStream, charset);

		StringBuffer sb = new StringBuffer();
		int c;
		while ((c = isr.read()) != -1) {
			sb.append((char) c);
		}
		isr.close();
		openStream.close();
		return sb.toString();
	}
}
